<template>
  <section class="bf-data-manager">
    <data-table :dt-option="dtOption"
                :dt-data="dtData"
                :dt-columns="dtColumns"
                @rowClick="rowClick"
                @rowEdit="rowEdit"
                @rowDel="rowDel"
                v-bind="$attrs">
    </data-table>
    <el-dialog v-if="showForm"
               :visible.sync="visible"
               append-to-body
               center
               :fullscreen="fullscreen"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :modal="false"
               v-bf-drag v-bf-resize="{resize:resizeFunc}"
               v-bind="$attrs">
      <el-form :model="formData"
               :label-width="formLabelWidth"
               ref="formData"
               class="data-form">
        <el-row>
          <el-col v-for="(item,index) in formItem" :key="index"
                  :xs="24" :sm="24" :md="12">
            <el-form-item :label="item.name!=='checkbox'?(item.label||''):''"
                          :prop="item.model"
                          :rules="item.rules || []">
              <el-input v-if="item.name=='input'"
                        v-model="formData[item.model]"
                        :type="item.formType||'text'"
                        :clearable="item.clearable||true"
                        :disabled="item.disabled||false"
                        :suffix-icon="item.suffixIcon||''"
                        :prefix-icon="item.prefixIcon||''"
                        auto-complete="off"></el-input>
              <el-select v-if="item.name=='select'"
                         v-model="formData[item.model]"
                         :placeholder="item.placeholder||''"
                         :clearable="item.clearable||true"
                         :filterable="item.filterable||true"
                         :disabled="item.disabled||false"
                         :multiple="item.multiple||false">
                <el-option
                  v-for="opt in item.options||[]"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                  :disabled="opt.disabled">
                </el-option>
              </el-select>
              <el-date-picker v-if="item.name=='date'"
                              v-model="formData[item.model]"
                              :type="item.formType || 'datetime'"
                              :disabled="item.disabled||false"
                              :placeholder="item.placeholder||''"></el-date-picker>
              <el-color-picker v-if="item.name=='color'"
                               v-model="formData[item.model]"
                               :disabled="item.disabled||false"></el-color-picker>
              <el-checkbox v-if="item.name=='checkbox'"
                           v-model="formData[item.model]"
                           :disabled="item.disabled||false">
                <span v-text="(item.label||'')"></span>
              </el-checkbox>
              <el-checkbox-group v-if="item.name=='checkboxGroup'"
                                 v-model="formData[item.model]"
                                 :min="item.min||0"
                                 :max="item.max||99"
                                 :disabled="item.disabled||false">
                <el-checkbox v-for="(opt,index) in item.options||[]"
                             :key="index" :label="opt">
                  <span v-text="opt"></span>
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="dialog-footer align-center">
              <el-button v-if="actionType==1"
                         type="primary"
                         @click="add">添加
              </el-button>
              <el-button v-if="actionType==2"
                         type="warning"
                         @click="update">更新
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </section>
</template>

<script lang="ts">
  import {Vue, Component, Prop, Emit} from 'vue-property-decorator'
  import {State, Mutation} from 'vuex-class'
  import bfProto from 'src/modules/proto/index'
  import bfConsole from 'src/utils/bf-console'

  @Component({
    components: {
      dataTable: () => import(/* webpackChunkName: "dataTable" */ './dataTable.vue')
    }
  })
  export default class editTable extends Vue {
    showForm: boolean = false;
    visible: boolean = false;
    actionType: number = 1;
    formData: object = {};

    @Mutation setUnitData;
    @Mutation delUnitData;


    update(): void {
      let $form: any = this.$refs['formData'];
      $form.validate((valid) => {
        if (valid) {
          this.visible = false;
          let data = {
            id: ""
          };
          data = Object.assign(data, this.formData);
          bfProto.sendMessage(this.rpcCmd, data, this.msgType)
            .then((res: any) => {
              bfConsole.log("update success:", res);
              this.setUnitData({[data.id]: data});
              this.updateData(data);
            }).catch(err => {
            bfConsole.error(err);
          });
        } else {
          bfConsole.warn('form validate error');
          return false;
        }
      });
    }

    add(): void {
      let $form: any = this.$refs['formData'];
      $form.validate((valid) => {
        if (valid) {
          this.visible = false;
          let data = {
            id: ""
          };
          data = Object.assign(data, this.formData);
          data.id = Math.random().toString(36).substr(2, 10);
          bfProto.sendMessage(this.rpcCmd, data, this.msgType)
            .then((res: any) => {
              bfConsole.log("add success:", res);
              this.setUnitData({[data.id]: data});
              this.addData(data);
            }).catch(err => {
            bfConsole.error(err);
          });
        } else {
          bfConsole.warn('form validate error');
          return false;
        }
      });
    }

    rowEdit(data: object, type?: number): void {
      // 设置表单按钮操作类型，添加或更新
      this.actionType = type || 1;

      // 打开表单编辑窗口
      if (!this.showForm) {
        this.showForm = true;
      }
      if (!this.visible) {
        this.visible = true;
      }

      // 清空表单元素值，并移除验证信息
      let $form: any = this.$refs['formData'];
      $form && $form.resetFields();

      // 将需要编辑的数据赋值给表单元素
      if (data) {
        this.$set(this, 'formData', Object.assign({}, data));
      } else {
        this.initFormData();
      }
    }

    rowDel(data: object): void {
      this.delUnitData(data);
      this.deleteData(data);
    }

    initFormData() {
      for (let i = 0; i < this.formItem.length; i++) {
        let item: editFormItem | any = this.formItem[i];
        let modelVal: any[] | string = "";
        if (!item.defauleVal) {
          switch (item.modelType) {
            case "array":
              modelVal = [];
              break;
            case "string":
            default:
              modelVal = "";
              break;
          }
        }
        // 向Vue实例数据指定对象添加响应式属性
        this.$set(this.formData, item.model, (item.defauleVal || modelVal));
      }
      this.$set(this.formData, "id", "");
    }

    mounted(): void {
      this.initFormData();
    }

    resizeFunc(data) {
      bfConsole.log("resizeFunc", data);
    }

    @Prop({
      default: () => {
        return {}
      }
    })
    dtOption: any;

    @Prop({
      default: () => {
        return []
      }
    })
    dtColumns: any[];

    @Prop({
      default: () => {
        return []
      }
    })
    dtData: any[];


    @Prop({
      required: true
    })
    formItem: editFormItem[] | any[];

    @Prop({
      default: "100px"
    })
    formLabelWidth: string;

    @Prop({
      required: true
    })
    msgType: string;
    @Prop({
      required: true
    })
    rpcCmd: number;

    @Emit('rowClick')
    rowClick(data: any) {
    }

    @Emit('add-data')
    addData(data: any) {
    }

    @Emit('up-data')
    updateData(data: any) {
    }

    @Emit('del-data')
    deleteData(data: any) {
    }


    get fullscreen() {
      return false;
    }
  }

</script>

<style lang="scss">
  .data-form .el-select,
  .data-form .el-date-editor {
    width: 100%;
  }

  .align-center {
    text-align: center;
  }

  @media screen and (min-width: 2560px) {
    .dialog-footer .el-button {
      width: 25%;
    }
  }

  @media screen and (max-width: 2559px) {
    .dialog-footer .el-button {
      width: 30%;
    }
  }

  @media screen and (max-width: 1919px) {
    .dialog-footer .el-button {
      width: 40%;
    }
  }

  @media screen and (max-width: 1199px) {
    .dialog-footer .el-button {
      width: 50%;
    }
  }

  @media screen and (max-width: 991px) {
    .dialog-footer .el-button {
      width: 65%;
    }
  }

  @media screen and (max-width: 767px) {
    .dialog-footer .el-button {
      width: 80%;
    }
  }
</style>
